namespace DotNetNuke.Common.Utilities
{
    using DotNetNuke.Common;
    using DotNetNuke.Services.Upgrade;
    using Microsoft.VisualBasic;
    using System;
    using System.IO;
    using System.Runtime.CompilerServices;
    using System.Text.RegularExpressions;
    using System.Web;

    /// -----------------------------------------------------------------------------
    /// Namespace:  DotNetNuke.Common.Utilities
    /// Project:    DotNetNuke
    /// Class:      HtmlUtils
    /// -----------------------------------------------------------------------------
    /// <summary>
    /// HtmlUtils is a Utility class that provides Html Utility methods
    /// </summary>
    /// <remarks>
    /// </remarks>
    /// <history>
    /// [cnurse]	11/16/2004	documented
    /// </history>
    /// -----------------------------------------------------------------------------
    public class HtmlUtils
    {
        /// -----------------------------------------------------------------------------
        /// <summary>
        /// Clean removes any HTML Tags, Entities (and optionally any punctuation) from
        /// a string
        /// </summary>
        /// <remarks>
        /// </remarks>
        /// <param name="HTML">The Html to clean</param>
        /// <param name="RemovePunctuation">A flag indicating whether to remove punctuation</param>
        /// <returns>The cleaned up string</returns>
        /// <history>
        /// [cnurse]	11/16/2004	created
        /// </history>
        /// -----------------------------------------------------------------------------
        public static string Clean(string HTML, bool RemovePunctuation)
        {
            HTML = StripEntities(HTML, true);
            HTML = StripTags(HTML, true);
            if (RemovePunctuation)
            {
                HTML = StripPunctuation(HTML, true);
            }
            return HTML;
        }

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// Formats an Email address
        /// </summary>
        /// <param name="Email">The email address to format</param>
        /// <returns>The formatted email address</returns>
        /// <history>
        /// [cnurse]	09/29/2005	moved from Globals
        /// </history>
        /// -----------------------------------------------------------------------------
        public static string FormatEmail(string Email)
        {
            string FormatEmail = "";
            if ((Email.Length != 0) && (Strings.Trim(Email) != ""))
            {
                if (Email.IndexOf("@") != -1)
                {
                    FormatEmail = "<a href=\"mailto:" + Email + "\">" + Email + "</a>";
                }
                else
                {
                    FormatEmail = Email;
                }
            }
            return DotNetNuke.Common.Globals.CloakText(FormatEmail);
        }

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// FormatText replaces <br /> tags by LineFeed characters
        /// </summary>
        /// <remarks>
        /// </remarks>
        /// <param name="HTML">The HTML content to clean up</param>
        /// <returns>The cleaned up string</returns>
        /// <history>
        /// [cnurse]	12/13/2004	created
        /// </history>
        /// -----------------------------------------------------------------------------
        public static string FormatText(string HTML, bool RetainSpace)
        {
            string brMatch = @"\s*<\s*[bB][rR]\s*/\s*>\s*";
            if (RetainSpace)
            {
            }
            return Regex.Replace(HTML, brMatch, "\n");
        }

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// Format a domain name including link
        /// </summary>
        /// <param name="Website">The domain name to format</param>
        /// <returns>The formatted domain name</returns>
        /// <history>
        /// [cnurse]	09/29/2005	moved from Globals
        /// </history>
        /// -----------------------------------------------------------------------------
        public static string FormatWebsite(object Website)
        {
            string FormatWebsite = "";
            if (Information.IsDBNull(RuntimeHelpers.GetObjectValue(Website)))
            {
                return FormatWebsite;
            }
            if (Strings.Trim(Website.ToString()) == "")
            {
                return FormatWebsite;
            }
            if (Convert.ToBoolean(Strings.InStr(1, Website.ToString(), ".", CompareMethod.Binary)))
            {
                return ("<a href=\"" + Interaction.IIf(Convert.ToBoolean(Strings.InStr(1, Website.ToString(), "://", CompareMethod.Binary)), "", "http://").ToString() + Website.ToString() + "\">" + Website.ToString() + "</a>");
            }
            return Website.ToString();
        }

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// Shorten returns the first (x) characters of a string
        /// </summary>
        /// <remarks>
        /// </remarks>
        /// <param name="txt">The text to reduces</param>
        /// <param name="length">The max number of characters to return</param>
        /// <param name="suffix">An optional suffic to append to the shortened string</param>
        /// <returns>The shortened string</returns>
        /// <history>
        /// [cnurse]	11/16/2004	created
        /// </history>
        /// -----------------------------------------------------------------------------
        public static string Shorten(string txt, int length, string suffix)
        {
            if (txt.Length > length)
            {
                return (txt.Substring(0, length) + suffix);
            }
            return txt;
        }

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// StripEntities removes the HTML Entities from the content
        /// </summary>
        /// <remarks>
        /// </remarks>
        /// <param name="HTML">The HTML content to clean up</param>
        /// <param name="RetainSpace">Indicates whether to replace the Entity by a space (true) or nothing (false)</param>
        /// <returns>The cleaned up string</returns>
        /// <history>
        /// [cnurse]	11/16/2004	created
        /// </history>
        /// -----------------------------------------------------------------------------
        public static string StripEntities(string HTML, bool RetainSpace)
        {
            string RepString;
            if (RetainSpace)
            {
                RepString = " ";
            }
            else
            {
                RepString = "";
            }
            return Regex.Replace(HTML, "&[^;]*;", RepString);
        }

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// StripNonWord removes any Non-Word Character from the content
        /// </summary>
        /// <remarks>
        /// </remarks>
        /// <param name="HTML">The HTML content to clean up</param>
        /// <param name="RetainSpace">Indicates whether to replace the Non-Word Character by a space (true) or nothing (false)</param>
        /// <returns>The cleaned up string</returns>
        /// <history>
        /// [cnurse]	1/28/2005	created
        /// </history>
        /// -----------------------------------------------------------------------------
        public static string StripNonWord(string HTML, bool RetainSpace)
        {
            string RepString;
            if (RetainSpace)
            {
                RepString = " ";
            }
            else
            {
                RepString = "";
            }
            if (HTML == null)
            {
                return HTML;
            }
            return Regex.Replace(HTML, @"\W*", RepString);
        }

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// StripPunctuation removes the Punctuation from the content
        /// </summary>
        /// <remarks>
        /// </remarks>
        /// <param name="HTML">The HTML content to clean up</param>
        /// <param name="RetainSpace">Indicates whether to replace the Punctuation by a space (true) or nothing (false)</param>
        /// <returns>The cleaned up string</returns>
        /// <history>
        /// [cnurse]	11/16/2004	documented
        /// </history>
        /// -----------------------------------------------------------------------------
        public static string StripPunctuation(string HTML, bool RetainSpace)
        {
            string RepString;
            string punctuationMatch = @"[~!#\$%\^&*\(\)-+=\{\[\}\]\|;:\x22'<,>\.\?\\\t\r\v\f\n]";
            Regex afterRegEx = new Regex(punctuationMatch + @"\s");
            Regex beforeRegEx = new Regex(@"\s" + punctuationMatch);
            string retHTML = HTML + " ";
            if (RetainSpace)
            {
                RepString = " ";
            }
            else
            {
                RepString = "";
            }
            while (beforeRegEx.IsMatch(retHTML))
            {
                retHTML = beforeRegEx.Replace(retHTML, RepString);
            }
            while (afterRegEx.IsMatch(retHTML))
            {
                retHTML = afterRegEx.Replace(retHTML, RepString);
            }
            return retHTML;
        }

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// StripTags removes the HTML Tags from the content
        /// </summary>
        /// <remarks>
        /// </remarks>
        /// <param name="HTML">The HTML content to clean up</param>
        /// <param name="RetainSpace">Indicates whether to replace the Tag by a space (true) or nothing (false)</param>
        /// <returns>The cleaned up string</returns>
        /// <history>
        /// [cnurse]	11/16/2004	documented
        /// </history>
        /// -----------------------------------------------------------------------------
        public static string StripTags(string HTML, bool RetainSpace)
        {
            string RepString;
            if (RetainSpace)
            {
                RepString = " ";
            }
            else
            {
                RepString = "";
            }
            return Regex.Replace(HTML, "<[^>]*>", RepString);
        }

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// StripWhiteSpace removes the WhiteSpace from the content
        /// </summary>
        /// <remarks>
        /// </remarks>
        /// <param name="HTML">The HTML content to clean up</param>
        /// <param name="RetainSpace">Indicates whether to replace the WhiteSpace by a space (true) or nothing (false)</param>
        /// <returns>The cleaned up string</returns>
        /// <history>
        /// [cnurse]	12/13/2004	documented
        /// </history>
        /// -----------------------------------------------------------------------------
        public static string StripWhiteSpace(string HTML, bool RetainSpace)
        {
            string RepString;
            if (RetainSpace)
            {
                RepString = " ";
            }
            else
            {
                RepString = "";
            }
            return Regex.Replace(HTML, @"\s+", RepString);
        }

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// WriteError outputs an Error Message during Install/Upgrade etc
        /// </summary>
        /// <remarks>
        /// </remarks>
        /// <param name="response">The ASP.Net Response object</param>
        /// <param name="file">The filename where the Error Occurred</param>
        /// <param name="message">The error message</param>
        /// <history>
        /// [cnurse]	02/21/2005	created
        /// </history>
        /// -----------------------------------------------------------------------------
        public static void WriteError(HttpResponse response, string file, string message)
        {
            response.Write("<h2>Error Details</h2>");
            response.Write("<table cellspacing=0 cellpadding=0 border=0>");
            response.Write("<tr><td><b>File</b></td><td><b>" + file + "</b></td></tr>");
            response.Write("<tr><td><b>Error</b>&nbsp;&nbsp;</td><td><b>" + message + "</b></td></tr>");
            response.Write("</table>");
            response.Write("<br><br>");
            response.Flush();
        }

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// WriteFeedback outputs a Feedback Line during Install/Upgrade etc
        /// </summary>
        /// <remarks>
        /// </remarks>
        /// <param name="response">The ASP.Net Response object</param>
        /// <param name="message">The feedback message</param>
        /// <history>
        /// [cnurse]	02/21/2005	created
        /// </history>
        /// -----------------------------------------------------------------------------
        public static void WriteFeedback(HttpResponse response, int indent, string message)
        {
            bool showInstallationMessages = true;
            if (Config.GetSetting("ShowInstallationMessages") != null)
            {
                showInstallationMessages = bool.Parse(Convert.ToString(Config.GetSetting("ShowInstallationMessages")));
            }
            if (showInstallationMessages)
            {
                TimeSpan timeElapsed = DotNetNuke.Services.Upgrade.Upgrade.RunTime;
                string strMessage = timeElapsed.ToString().Substring(0, timeElapsed.ToString().LastIndexOf(".") + 4) + " -";
                int refIntHelperL0 = indent;
                for (int i = 0; i <= refIntHelperL0; i++)
                {
                    strMessage = strMessage + "&nbsp;";
                }
                strMessage = strMessage + message;
                HttpContext.Current.Response.Write(strMessage);
                HttpContext.Current.Response.Flush();
            }
        }

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// WriteFooter outputs the Footer during Install/Upgrade etc
        /// </summary>
        /// <remarks>
        /// </remarks>
        /// <param name="response">The ASP.Net Response object</param>
        /// <history>
        /// [cnurse]	02/21/2005	created
        /// </history>
        /// -----------------------------------------------------------------------------
        public static void WriteFooter(HttpResponse response)
        {
            response.Write("</body>");
            response.Write("</html>");
            response.Flush();
        }

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// WriteHeader outputs the Header during Install/Upgrade etc
        /// </summary>
        /// <remarks>
        /// </remarks>
        /// <param name="response">The ASP.Net Response object</param>
        /// <param name="mode">The mode Install/Upgrade etc</param>
        /// <history>
        /// [cnurse]	02/21/2005	created
        /// </history>
        /// -----------------------------------------------------------------------------
        public static void WriteHeader(HttpResponse response, string mode)
        {
            response.Buffer = false;
            if (!File.Exists(HttpContext.Current.Server.MapPath("~/Install/Install.htm")) && File.Exists(HttpContext.Current.Server.MapPath("~/Install/Install.template.htm")))
            {
                File.Copy(HttpContext.Current.Server.MapPath("~/Install/Install.template.htm"), HttpContext.Current.Server.MapPath("~/Install/Install.htm"));
            }
            if (File.Exists(HttpContext.Current.Server.MapPath("~/Install/Install.htm")))
            {
                StreamReader objStreamReader = File.OpenText(HttpContext.Current.Server.MapPath("~/Install/Install.htm"));
                string strHTML = objStreamReader.ReadToEnd();
                objStreamReader.Close();
                response.Write(strHTML);
            }
            string refStringHelperL0 = mode;
            if (refStringHelperL0 == "install")
            {
                response.Write("<h1>Installing DotNetNuke</h1>");
            }
            else if (refStringHelperL0 == "upgrade")
            {
                response.Write("<h1>Upgrading DotNetNuke</h1>");
            }
            else if (refStringHelperL0 == "addPortal")
            {
                response.Write("<h1>Adding New Portal</h1>");
            }
            else if (refStringHelperL0 == "installResources")
            {
                response.Write("<h1>Installing Resources</h1>");
            }
            else if (refStringHelperL0 == "executeScripts")
            {
                response.Write("<h1>Executing Scripts</h1>");
            }
            else if (refStringHelperL0 == "none")
            {
                response.Write("<h1>Nothing To Install At This Time</h1>");
            }
            else if (refStringHelperL0 == "noDBVersion")
            {
                response.Write("<h1>DotNetNuke Not Installed</h1>");
            }
            else if (refStringHelperL0 == "error")
            {
                response.Write("<h1>Error Installing DotNetNuke</h1>");
            }
            else
            {
                response.Write("<h1>" + mode + "</h1>");
            }
            response.Flush();
        }
    }
}

